package com.czk.socket.practice;

import org.junit.Test;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

/**
 * @Author:ChenZhangKun
 * @Date: 2021/10/14 11:19
 */
public class BlockIoTransferFile {
    @Test
    public void client() throws IOException {
        SocketChannel socketChannel = SocketChannel.open(new InetSocketAddress("localhost", 8081));
        // 创建文件
        /// 设置channel
        FileChannel open = FileChannel.open(Paths.get("D:\\简历\\罗琴.doc"), StandardOpenOption.READ);
        ByteBuffer buffer = ByteBuffer.allocate(1024);
        // 读取
        while ((open.read(buffer)) != -1) {
            buffer.flip();
            socketChannel.write(buffer);
            // 情空
            buffer.clear();
        }
        open.close();
        socketChannel.close();
    }

    @Test
    public void server() throws IOException {
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        // 创建缓冲区
        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
        // 绑定端口
        serverSocketChannel.bind(new InetSocketAddress("localhost", 8081));
        // 创建文件输入
        FileChannel fileChanel = FileChannel.open(Paths.get("D:\\简历\\1\\4.doc"), StandardOpenOption.READ, StandardOpenOption.CREATE, StandardOpenOption.WRITE);
        // 阅读
        SocketChannel accept = serverSocketChannel.accept();
        while ((accept.read(byteBuffer) != -1)) {
            // 切换状态
            byteBuffer.flip();
            // 读取
            fileChanel.write(byteBuffer);
            byteBuffer.clear();
        }
        // 关闭
        fileChanel.close();
        serverSocketChannel.close();
    }


}
